
#import "GameManager.h"
#import "Box2dWrapper.h"

int W=320;
int H=480;

@implementation GameManager

#pragma mark ============================= Init Methods ================================

+ (GameManager*) getInstance  {
    
    static GameManager* gameManager;
		
	if (!gameManager) {
        gameManager = [[GameManager alloc] init];
        NSLog(@"gameManager Singleton created!");
		[gameManager preloader];            
	}
	    
    return gameManager;
}

- (void) preloader {
    sprites = [[NSMutableArray alloc] initWithCapacity:20];
    newSprites = [[NSMutableArray alloc] initWithCapacity:20];
    destroyableSprites = [[NSMutableArray alloc] initWithCapacity:20];
    tiles = [[NSMutableArray alloc] initWithCapacity:50]; 
   
    //Preload OGL-Textures       
    [self getTex: @"block32x32.png" isImage: YES];
    [self getTex: @"block16x16.png" isImage: YES];

    //Optional
    //[self getTex: @"abc" isImage: NO];
    
    [Box2dWrapper getInstance]; //init box2d   
     
    [[Box2dWrapper getInstance] createStaticBody: CGRectMake(-100, H+1, W+200, 1)]; 
    
    [self setOGLProjection];
    
    state = LOAD_GAME;
}

- (void) loadGame { 
    [sprites removeAllObjects];
    [newSprites removeAllObjects];
    [destroyableSprites removeAllObjects];      
    
    //Optional
    //[self removeFromDictionary: @"myTex1.png"];
}

#pragma mark ============================= Game Handler ===============================

- (void) touchBegan: (CGPoint) p {    
    [self handleStates];

    if (state == PLAY_GAME) {        
        if (p.y < H/2) {
            //dynamic box2d body
            SpriteB2 *sprite = [[SpriteB2 alloc] initWithPic: @"block32x32.png" 
                                                    frameCnt: 1                                     
                                                   frameStep: 0
                                                       speed: CGPointMake(0, 0)
                                                         pos: p];     
            [newSprites addObject: sprite];
            [sprite release];
        } else {
            //static box2d body
            TileB2 *tile = [[TileB2 alloc] initWithPic: @"block16x16.png" 
                                                   pos: p];
            [tiles addObject: tile];
            [tile release];    
        }
    }    
}

- (void) touchMoved: (CGPoint) p {
    //if (state == PLAY_GAME) {
    //    [self touchBegan: p];
    //}    
}

- (void) touchEnded {
    if (state == PLAY_GAME) {
    }   
}

- (void) handleStates {   
    if (state == START_GAME) {
        state = PLAY_GAME;
    }
    else if (state == GAME_OVER) {
        state = LOAD_GAME;
    }
}

- (void) drawStatesWithFrame: (CGRect) frame { 
    switch (state) {
        case LOAD_GAME: 
            [self loadGame];
            state = START_GAME;
            break;
        case START_GAME:             
            [self drawOGLString: @"Tap screen to start!" at: CGPointMake(0, 0)];
            [self drawOGLString: @"Above line: dynamic body" at: CGPointMake(0, 25)];
            [self drawOGLString: @"Below line: static body" at: CGPointMake(0, 50)];
            break;    
        case PLAY_GAME:
            [self playGame];
            break;
        case GAME_OVER:
            [self playGame];
            [self drawOGLString: @"G A M E  O V E R" at: CGPointMake(0, 0)];
            break;             
        default: NSLog(@"ERROR: Unknown state: %i", state);
            break;
    }    
}	 

- (void) playGame {
    timer++;    
   
    [self manageSprites];             
    [self renderSprites];  
    
    [self drawOGLLineFrom: CGPointMake(0, H/2) to: CGPointMake(W, H/2)];
    
    [[Box2dWrapper getInstance] update];        
    
    for (TileB2 *tile in tiles) { 
        [tile draw];
    } 
} 

- (void) checkSprite: (Sprite *) sprite {
    //if ([sprite getType] == CUBE) {                
    //    for (Sprite *sprite2test in sprites) {        
    //    } 
    //}  
}

#pragma mark ============================= OGL Methods ===============================

- (void) setOGLProjection {
    //Set View
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity();    
    glOrthof(0, W, H, 0, 0, 1);

    glMatrixMode(GL_MODELVIEW);
    glEnableClientState(GL_VERTEX_ARRAY); 
    glDisable(GL_DEPTH_TEST); //2D only
} 

- (void) drawOGLLineFrom: (CGPoint) p1 to: (CGPoint) p2 {
    GLshort vertices[ ] = { 
        p1.x, p1.y,
        p2.x, p2.y        
    };      

    glVertexPointer(2, GL_SHORT, 0, vertices);           
    glColor4f(1, 1, 0, 1);
    glDrawArrays(GL_LINES, 0, 2);       
}

- (void) drawOGLRect: (CGRect) rect {    
    GLshort vertices[ ] = {
        0,                  rect.size.height, 
        rect.size.width,    rect.size.height, 
        0,                  0, 
        rect.size.width,    0  
    };
        
    glVertexPointer(2, GL_SHORT, 0, vertices);           
    glColor4f(1, 1, 0, 1);
    
    glPushMatrix();      
    glTranslatef(rect.origin.x, rect.origin.y, 0);          
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); 
    glPopMatrix();      
}

- (void) drawOGLImg: (NSString*) picName at: (CGPoint) p {    
    Tex *tex = [self getTex: picName isImage: YES]; 
    if (tex) {
        [tex drawAt: p];
    }
}

- (CGSize) getOGLImgDimension: (NSString*) picName {    
    Tex *tex = [self getTex: picName isImage: YES]; 
    if (tex) {
        return CGSizeMake([tex getWidth], [tex getHeight]);
    }
    return CGSizeMake(0, 0); 
}

- (void) drawOGLString: (NSString*) text at: (CGPoint) p {    
    Tex *tex = [self getTex: text isImage: NO]; 
    if (tex) {
        [tex drawAt: p];
    }
}

- (Tex *) getTex: (NSString*) name isImage: (bool) imgFlag { 
	Tex *tex = [[self getDictionary] objectForKey: name];
	if (!tex) {
		tex = [[Tex alloc] init];
        if (imgFlag) {            
            [tex createTexFromImage: name];             
        } else {
            [tex createTexFromString: name];
        }    
        [[self getDictionary] setObject: tex forKey: name];
        NSLog(@"%@ set as Tex in dictionary.", name);
        [tex release];         
	}          
	return tex;  
}

#pragma mark ============================= Helper Methods ===============================

- (void) setState: (int) stt {
    state = stt;
}

- (void) manageSprites {
    //NSLog(@"Sprites: %i destroyable: %i new: %i", [sprites count], [destroyableSprites count], [newSprites count]);
    
    //Cleanup 
    for (Sprite *destroyableSprite in destroyableSprites) { 
        for (Sprite *sprite in sprites) { 
            if (destroyableSprite == sprite) { 
                [sprites removeObject: sprite];
                break;
            }
        }   
    }  
    
    for (Sprite *newSprite in newSprites){ 
        [sprites addObject: newSprite];   
    } 
    
    [destroyableSprites removeAllObjects]; 
    [newSprites removeAllObjects];
}

- (void) renderSprites {
    for (Sprite *sprite in sprites) { 
        if ([sprite isActive]) {             
            [self checkSprite: sprite];
            [sprite draw];                 
        } else {
            [destroyableSprites addObject: sprite]; 
        }    
    }                
}

- (NSMutableDictionary *) getDictionary {
	if (!dictionary) { //Hashtable
		dictionary = [[NSMutableDictionary alloc] init]; 
		NSLog(@"Dictionary created!");
	}
	return dictionary;
}

- (void) removeFromDictionary: (NSString*) name {
    [[self getDictionary] removeObjectForKey: name];
} 

- (int) getRndBetween: (int) bottom and: (int) top {		
	int rnd = bottom + (arc4random() % (top+1-bottom)); 
	return rnd;
} 

- (void) dealloc {        
    [sprites release];
    [newSprites release];
    [destroyableSprites release];
    [dictionary release];
    [super dealloc];
}

@end
